package com.pocketmenu.ui;

import java.text.DecimalFormat;
import java.util.Date;

import com.pocketmenu.business.Constants;
import com.pocketmenu.business.OrderItemCursorAdapter;
import com.pocketmenu.business.SMS;
import com.pocketmenu.persistence.CheckDataSource;
import com.pocketmenu.persistence.Order;
import com.pocketmenu.persistence.OrderDataSource;
import com.pocketmenu.persistence.Restaurant;
import com.pocketmenu.persistence.RestaurantDataSource;
import com.pocketmenu.persistence.SQLiteHelper;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.support.v4.app.Fragment;
import android.support.v4.app.NavUtils;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;

import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;

import android.widget.SimpleCursorAdapter;
import android.widget.TextView;


public class CheckActivity extends Fragment {
	
	private int orderTotal;
	private int subtotal;
	private double vat;		
    
	private Activity getCurrentActivity()
	{
		return getActivity();
	}
	
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (container == null) {            
            return null;
        }				        
        		
		//load item listview      
		if(Constants.idOrder != 0)
		{
			View fragmentView = inflater.inflate(R.layout.activity_order, container, false);			
			loadCheckListView(fragmentView);
			return fragmentView;
		}
		else
		{
			View fragmentView = inflater.inflate(R.layout.activity_order_empty, container, false);						
			return fragmentView;
		}
        
	}
	
	private void loadCheckListView(View view)
	{
		String[] from = new String[]{SQLiteHelper.COLUMN_ITEM_NAME, SQLiteHelper.COLUMN_ITEM_PRICE, SQLiteHelper.COLUMN_ORDER_ITEM_QUANTITY};
        
        int[] to = new int[]{R.id.tvItemName,R.id.tvItemTotalPrice, R.id.tvItemQuantity};
               
        OrderDataSource datasource = new OrderDataSource(getCurrentActivity());
        datasource.open();
                
        Cursor cursor = datasource.getOrderItemList(Constants.idOrder);       
        SimpleCursorAdapter adp= new OrderItemCursorAdapter(getCurrentActivity(), R.layout.single_order_item, cursor, from, to, null);
        
        ListView listView = (ListView) view.findViewById(R.id.lvCheckItems);   
        
        View footerView = View.inflate(getCurrentActivity(), R.layout.footer_check, null);       
        setFooterValues(footerView, cursor);
        listView.addFooterView(footerView);
        
        listView.setAdapter(adp);
        datasource.close();	
	
	}
	
    private void setFooterValues(View footerView, Cursor cursor)
    {
    	subtotal = 0;
    	cursor.moveToFirst();
    	int itemTotalColumnIndex = cursor.getColumnIndex(SQLiteHelper.COLUMN_ITEM_PRICE);    	
    	int itemQuantityColumnIndex = cursor.getColumnIndex(SQLiteHelper.COLUMN_ORDER_ITEM_QUANTITY);
    	      
	    while (!cursor.isAfterLast()) {
	      
	      subtotal += (cursor.getInt(itemTotalColumnIndex) * cursor.getInt(itemQuantityColumnIndex));	      
	      cursor.moveToNext();	      
	    }
	    
	    DecimalFormat df = new DecimalFormat("#,###,###");	    
	    
	    TextView tvSubtotalTemp = (TextView) footerView.findViewById(R.id.tvSubtotal);
        tvSubtotalTemp.setText("$" + df.format(subtotal));
        
        TextView tvVatTemp = (TextView) footerView.findViewById(R.id.tvVat);
                       
        vat = subtotal * 0.16;       
        tvVatTemp.setText("$" + df.format(vat));
        
        TextView tvTipTemp = (TextView) footerView.findViewById(R.id.etTip);
        
        double tip = subtotal * 0.1;
        DecimalFormat dfTip = new DecimalFormat("#");
        tvTipTemp.setText(dfTip.format(tip));                
        
        TextView tvTotalTemp = (TextView) footerView.findViewById(R.id.tvTotal);
        
        orderTotal =  (int) (subtotal + vat + tip);
        tvTotalTemp.setText("$" + df.format(orderTotal));
        
        tvTipTemp.addTextChangedListener(new TextWatcher() {
			public void afterTextChanged(Editable s) {
				
				int tip = s.toString() != null && s.toString().length() != 0 ? Integer.parseInt(s.toString()) : 0;
				calculateTotal(tip);
			}

			public void beforeTextChanged(CharSequence s, int start, int count,int after) {}
			public void onTextChanged(CharSequence s, int start, int before,int count) {}
			
		} );
        
        TextView tvTableCodeTemp = (TextView) footerView.findViewById(R.id.tvTableCode);
        
        OrderDataSource orderDataSource = new OrderDataSource(getCurrentActivity());
        orderDataSource.open();
        Order order = orderDataSource.getOrder(Constants.idOrder);
        orderDataSource.close();
        
        tvTableCodeTemp.setText(order.getTableCode());
        
        cursor.moveToFirst();
    }              
    
    /*
    private boolean sendCheck()
    {
    	View lvCheckItemsTemp = findViewById(R.id.lvCheckItems);  
    	View rlFooterCheck = lvCheckItemsTemp.findViewById(R.id.rlFooterCheck);
    	
    	TextView tvTableCodeTemp = (TextView) rlFooterCheck.findViewById(R.id.tvTableCode);   
    	EditText etTipTemp = (EditText) rlFooterCheck.findViewById(R.id.etTip);
    	
    	RadioButton rbCash = (RadioButton) rlFooterCheck.findViewById(R.id.rbCash);
    	RadioButton rbCard = (RadioButton) rlFooterCheck.findViewById(R.id.rbCard);
    	
    	String payment = rbCash.isChecked() ? rbCash.getText().toString() : rbCard.getText().toString();
    	
    	boolean messageSent = false;
    		
    	RestaurantDataSource restaurantDatasource = new RestaurantDataSource(this);
    	CheckDataSource checkDatasource = new CheckDataSource(this);
    	
    	checkDatasource.open();
    	restaurantDatasource.open();
    	
    	Date now = new Date();    	    	
    	Restaurant restaurantTemp = restaurantDatasource.getRestaurant(idRestaurant);
    	
    	String tipString = etTipTemp.getText().toString(); 
    	int tip = tipString != null && tipString.length() != 0 ? Integer.parseInt(tipString.toString()) : 0;    	
    	
    	messageSent = SMS.sendSMS(restaurantTemp.getSms(), "Enviar cuenta a la Mesa # " + tvTableCodeTemp.getText().toString() + "\nPropina: " + etTipTemp.getText().toString() + "\nTotal: " + String.valueOf(orderTotal)  +  "\nPago: " + payment);
    	checkDatasource.create(orderTotal, messageSent, tvTableCodeTemp.getText().toString(), tip, now, idOrder);
    	
    	restaurantDatasource.close();
    	checkDatasource.close();	
    	
    	return messageSent;
    	
    }
    */
    /*
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                NavUtils.navigateUpFromSameTask(this);
                return true;
            case R.id.miSendCheck:   
            	boolean sent = sendCheck();
            	if(sent)
            	{
            		startItemListActivity("La solicitud de tu cuenta fue enviada ;)");
            		finish();
            	}            	         		
      	      break;
      	    case R.id.miItemList:
      	    	startItemListActivity(null);    
      	    	finish();
      	      break;
      	    case R.id.miRestaurant:
      	    	Intent intentR = new Intent(getApplicationContext(), RestaurantActivity.class);            	
  	    		startActivity(intentR);
  	    		finish();
  	    		break;
      	    default:
      	      break;
        }
        return super.onOptionsItemSelected(item);
    } 
    
    private void startItemListActivity(String message)
    {
    	Intent intent = new Intent(getApplicationContext(), ItemListActivity.class);
    	intent.putExtra(Constants.EXTRA_ORDER_ID, idOrder);
    	intent.putExtra(Constants.EXTRA_RESTAURANT_ID, idRestaurant);
    	intent.putExtra(Constants.EXTRA_MESSAGE, message);
    	startActivity(intent);  
    }
    
    */
    /*
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_check);
        
        String[] from = new String[]{SQLiteHelper.COLUMN_ITEM_NAME, SQLiteHelper.COLUMN_ITEM_PRICE, SQLiteHelper.COLUMN_ORDER_ITEM_QUANTITY};
        
        int[] to = new int[]{R.id.tvItemName,R.id.tvItemTotalPrice, R.id.tvItemQuantity};
               
        OrderDataSource datasource = new OrderDataSource(this);
        datasource.open();
        
        Intent intent = getIntent();
        idOrder = intent.getIntExtra(Constants.EXTRA_ORDER_ID, 0);
        idRestaurant = intent.getIntExtra(Constants.EXTRA_RESTAURANT_ID, 0);
        
        Cursor cursor = datasource.getOrderItemList(idOrder);       
        SimpleCursorAdapter adp= new OrderItemCursorAdapter(this, R.layout.single_order_item, cursor, from, to);
        
        ListView listView = (ListView) findViewById(R.id.lvCheckItems);   
        
        View footerView = View.inflate(this, R.layout.footer_check, null);       
        setFooterValues(footerView, cursor);
        listView.addFooterView(footerView);
        
        listView.setAdapter(adp);
        datasource.close();
    }
*/
    /*
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_check, menu);
        return true;
    }
    */
    
    private void calculateTotal(int tip)
    {
    	View lvCheckItemsTemp = getCurrentActivity().findViewById(R.id.lvCheckItems);  
    	View rlFooterCheck = lvCheckItemsTemp.findViewById(R.id.rlFooterCheck);
    	
    	TextView tvTotalTemp = (TextView) rlFooterCheck.findViewById(R.id.tvTotal);
    	
    	orderTotal = (int) (subtotal + vat + tip);
    	
    	DecimalFormat df = new DecimalFormat("#,###,###");
    	tvTotalTemp.setText(df.format(orderTotal));
    }
    
}
